home *** CD-ROM | disk | FTP | other *** search
/ IRIX 5.3 for Indy R4400 / IRIX 5.3 for Indy R4400 175MHz.img / dist / eoe2.idb / usr / src / rcs / DIFFsource.Z / DIFFsource / analyze.c < prev    next >
C/C++ Source or Header  |  1995-02-28  |  31KB  |  1,077 lines

  1. /* Analyze file differences for GNU DIFF.
  2.    Copyright (C) 1988, 1989 Free Software Foundation, Inc.
  3.  
  4. This file is part of GNU DIFF.
  5.  
  6. GNU DIFF is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 1, or (at your option)
  9. any later version.
  10.  
  11. GNU DIFF is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. GNU General Public License for more details.
  15.  
  16. You should have received a copy of the GNU General Public License
  17. along with GNU DIFF; see the file COPYING.  If not, write to
  18. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  19.  
  20. /* The basic algorithm is described in: 
  21.    "An O(ND) Difference Algorithm and its Variations", Eugene Myers,
  22.    Algorithmica Vol. 1 No. 2, 1986, p 251.  */
  23.  
  24. #include "diff.h"
  25.  
  26. struct change *find_change ();
  27. void finish_output ();
  28. void print_context_header ();
  29. void print_context_script ();
  30. void print_ed_script ();
  31. void print_ifdef_script ();
  32. void print_normal_script ();
  33. void print_rcs_script ();
  34. void pr_forward_ed_script ();
  35. void setup_output ();
  36.  
  37. extern int no_discards;
  38. extern int files_are_identical;
  39.  
  40. static int *xvec, *yvec;    /* Vectors being compared. */
  41. static int *fdiag;        /* Vector, indexed by diagonal, containing
  42.                    the X coordinate of the point furthest
  43.                    along the given diagonal in the forward
  44.                    search of the edit matrix. */
  45. static int *bdiag;        /* Vector, indexed by diagonal, containing
  46.                    the X coordinate of the point furthest
  47.                    along the given diagonal in the backward
  48.                    search of the edit matrix. */
  49.  
  50. /* Find the midpoint of the shortest edit script for a specified
  51.    portion of the two files.
  52.  
  53.    We scan from the beginnings of the files, and simultaneously from the ends,
  54.    doing a breadth-first search through the space of edit-sequence.
  55.    When the two searches meet, we have found the midpoint of the shortest
  56.    edit sequence.
  57.  
  58.    The value returned is the number of the diagonal on which the midpoint lies.
  59.    The diagonal number equals the number of inserted lines minus the number
  60.    of deleted lines (counting only lines before the midpoint).
  61.    The edit cost is stored into *COST; this is the total number of
  62.    lines inserted or deleted (counting only lines before the midpoint).
  63.  
  64.    This function assumes that the first lines of the specified portions
  65.    of the two files do not match, and likewise that the last lines do not
  66.    match.  The caller must trim matching lines from the beginning and end
  67.    of the portions it is going to specify.
  68.  
  69.    Note that if we return the "wrong" diagonal value, or if
  70.    the value of bdiag at that diagonal is "wrong",
  71.    the worst this can do is cause suboptimal diff output.
  72.    It cannot cause incorrect diff output.  */
  73.  
  74. static int
  75. diag (xoff, xlim, yoff, ylim, cost)
  76.      int xoff, xlim, yoff, ylim;
  77.      int *cost;
  78. {
  79.   int *const fd = fdiag;    /* Give the compiler a chance. */
  80.   int *const bd = bdiag;    /* Additional help for the compiler. */
  81.   int *const xv = xvec;        /* Still more help for the compiler. */
  82.   int *const yv = yvec;        /* And more and more . . . */
  83.   const int dmin = xoff - ylim;    /* Minimum valid diagonal. */
  84.   const int dmax = xlim - yoff;    /* Maximum valid diagonal. */
  85.   const int fmid = xoff - yoff;    /* Center diagonal of top-down search. */
  86.   const int bmid = xlim - ylim;    /* Center diagonal of bottom-up search. */
  87.   int fmin = fmid, fmax = fmid;    /* Limits of top-down search. */
  88.   int bmin = bmid, bmax = bmid;    /* Limits of bottom-up search. */
  89.   int c;            /* Cost. */
  90.   int odd = fmid - bmid & 1;    /* True if southeast corner is on an odd
  91.                    diagonal with respect to the northwest. */
  92.  
  93.   fd[fmid] = xoff;
  94.   bd[bmid] = xlim;
  95.  
  96.   for (c = 1;; ++c)
  97.     {
  98.       int d;            /* Active diagonal. */
  99.       int big_snake = 0;
  100.  
  101.       /* Extend the top-down search by an edit step in each diagonal. */
  102.       fmin > dmin ? fd[--fmin - 1] = -1 : ++fmin;
  103.       fmax < dmax ? fd[++fmax + 1] = -1 : --fmax;
  104.       for (d = fmax; d >= fmin; d -= 2)
  105.     {
  106.       int x, y, oldx, tlo = fd[d - 1], thi = fd[d + 1];
  107.  
  108.       if (tlo >= thi)
  109.         x = tlo + 1;
  110.       else
  111.         x = thi;
  112.       oldx = x;
  113.       y = x - d;
  114.       while (x < xlim && y < ylim && xv[x] == yv[y])
  115.         ++x, ++y;
  116.       if (x - oldx > 20)
  117.         big_snake = 1;
  118.       fd[d] = x;
  119.       if (odd && bmin <= d && d <= bmax && bd[d] <= fd[d])
  120.         {
  121.           *cost = 2 * c - 1;
  122.           return d;
  123.         }
  124.     }
  125.  
  126.       /* Similar extend the bottom-up search. */
  127.       bmin > dmin ? bd[--bmin - 1] = INT_MAX : ++bmin;
  128.       bmax < dmax ? bd[++bmax + 1] = INT_MAX : --bmax;
  129.       for (d = bmax; d >= bmin; d -= 2)
  130.     {
  131.       int x, y, oldx, tlo = bd[d - 1], thi = bd[d + 1];
  132.  
  133.       if (tlo < thi)
  134.         x = tlo;
  135.       else
  136.         x = thi - 1;
  137.       oldx = x;
  138.       y = x - d;
  139.       while (x > xoff && y > yoff && xv[x - 1] == yv[y - 1])
  140.         --x, --y;
  141.       if (oldx - x > 20)
  142.         big_snake = 1;
  143.       bd[d] = x;
  144.       if (!odd && fmin <= d && d <= fmax && bd[d] <= fd[d])
  145.         {
  146.           *cost = 2 * c;
  147.           return d;
  148.         }
  149.     }
  150.  
  151.       /* Heuristic: check occasionally for a diagonal that has made
  152.      lots of progress compared with the edit distance.
  153.      If we have any such, find the one that has made the most
  154.      progress and return it as if it had succeeded.
  155.  
  156.      With this heuristic, for files with a constant small density
  157.      of changes, the algorithm is linear in the file size.  */
  158.  
  159.       if (c > 200 && big_snake && heuristic)
  160.     {
  161.       int best;
  162.       int bestpos;
  163.  
  164.       best = 0;
  165.       for (d = fmax; d >= fmin; d -= 2)
  166.         {
  167.           int dd = d - fmid;
  168.           if ((fd[d] - xoff)*2 - dd > 12 * (c + (dd > 0 ? dd : -dd)))
  169.         {
  170.           if (fd[d] * 2 - dd > best
  171.               && fd[d] - xoff > 20
  172.               && fd[d] - d - yoff > 20)
  173.             {
  174.               int k;
  175.               int x = fd[d];
  176.  
  177.               /* We have a good enough best diagonal;
  178.              now insist that it end with a significant snake.  */
  179.               for (k = 1; k <= 20; k++)
  180.             if (xvec[x - k] != yvec[x - d - k])
  181.               break;
  182.  
  183.               if (k == 21)
  184.             {
  185.               best = fd[d] * 2 - dd;
  186.               bestpos = d;
  187.             }
  188.             }
  189.         }
  190.         }
  191.       if (best > 0)
  192.         {
  193.           *cost = 2 * c - 1;
  194.           return bestpos;
  195.         }
  196.  
  197.       best = 0;
  198.       for (d = bmax; d >= bmin; d -= 2)
  199.         {
  200.           int dd = d - bmid;
  201.           if ((xlim - bd[d])*2 + dd > 12 * (c + (dd > 0 ? dd : -dd)))
  202.         {
  203.           if ((xlim - bd[d]) * 2 + dd > best
  204.               && xlim - bd[d] > 20
  205.               && ylim - (bd[d] - d) > 20)
  206.             {
  207.               /* We have a good enough best diagonal;
  208.              now insist that it end with a significant snake.  */
  209.               int k;
  210.               int x = bd[d];
  211.  
  212.               for (k = 0; k < 20; k++)
  213.             if (xvec[x + k] != yvec[x - d + k])
  214.               break;
  215.               if (k == 20)
  216.             {
  217.               best = (xlim - bd[d]) * 2 + dd;
  218.               bestpos = d;
  219.             }
  220.             }
  221.         }
  222.         }
  223.       if (best > 0)
  224.         {
  225.           *cost = 2 * c - 1;
  226.           return bestpos;
  227.         }
  228.     }
  229.     }
  230. }
  231.  
  232. /* Compare in detail contiguous subsequences of the two files
  233.    which are known, as a whole, to match each other.
  234.  
  235.    The results are recorded in the vectors files[N].changed_flag, by
  236.    storing a 1 in the element for each line that is an insertion or deletion.
  237.  
  238.    The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
  239.  
  240.    Note that XLIM, YLIM are exclusive bounds.
  241.    All line numbers are origin-0 and discarded lines are not counted.  */
  242.  
  243. static void
  244. compareseq (xoff, xlim, yoff, ylim)
  245.      int xoff, xlim, yoff, ylim;
  246. {
  247.   /* Slide down the bottom initial diagonal. */
  248.   while (xoff < xlim && yoff < ylim && xvec[xoff] == yvec[yoff])
  249.     ++xoff, ++yoff;
  250.   /* Slide up the top initial diagonal. */
  251.   while (xlim > xoff && ylim > yoff && xvec[xlim - 1] == yvec[ylim - 1])
  252.     --xlim, --ylim;
  253.   
  254.   /* Handle simple cases. */
  255.   if (xoff == xlim)
  256.     while (yoff < ylim)
  257.       files[1].changed_flag[files[1].realindexes[yoff++]] = 1;
  258.   else if (yoff == ylim)
  259.     while (xoff < xlim)
  260.       files[0].changed_flag[files[0].realindexes[xoff++]] = 1;
  261.   else
  262.     {
  263.       int c, d, f, b;
  264.  
  265.       /* Find a point of correspondence in the middle of the files.  */
  266.  
  267.       d = diag (xoff, xlim, yoff, ylim, &c);
  268.       f = fdiag[d];
  269.       b = bdiag[d];
  270.  
  271.       if (c == 1)
  272.     {
  273.       /* This should be impossible, because it implies that
  274.          one of the two subsequences is empty,
  275.          and that case was handled above without calling `diag'.
  276.          Let's verify that this is true.  */
  277.       abort ();
  278. #if 0
  279.       /* The two subsequences differ by a single insert or delete;
  280.          record it and we are done.  */
  281.       if (d < xoff - yoff)
  282.         files[1].changed_flag[files[1].realindexes[b - d - 1]] = 1;
  283.       else
  284.         files[0].changed_flag[files[0].realindexes[b]] = 1;
  285. #endif
  286.     }
  287.       else
  288.     {
  289.       /* Use that point to split this problem into two subproblems.  */
  290.       compareseq (xoff, b, yoff, b - d);
  291.       /* This used to use f instead of b,
  292.          but that is incorrect!
  293.          It is not necessarily the case that diagonal d
  294.          has a snake from b to f.  */
  295.       compareseq (b, xlim, b - d, ylim);
  296.     }
  297.     }
  298. }
  299.  
  300. /* Discard lines from one file that have no matches in the other file.
  301.  
  302.    A line which is discarded will not be considered by the actual
  303.    comparison algorithm; it will be as if that line were not in the file.
  304.    The file's `realindexes' table maps virtual line numbers
  305.    (which don't count the discarded lines) into real line numbers;
  306.    this is how the actual comparison algorithm produces results
  307.    that are comprehensible when the discarded lines are counted.
  308.  
  309.    When we discard a line, we also mark it as a deletion or insertion
  310.    so that it will be printed in the output.  */
  311.  
  312. void
  313. discard_confusing_lines (filevec)
  314.      struct file_data filevec[];
  315. {
  316.   unsigned int f, i;
  317.   char *discarded[2];
  318.   int *equiv_count[2];
  319.  
  320.   /* Allocate our results.  */
  321.   for (f = 0; f < 2; f++)
  322.     {
  323.       filevec[f].undiscarded
  324.     = (int *) xmalloc (filevec[f].buffered_lines * sizeof (int));
  325.       filevec[f].realindexes
  326.     = (int *) xmalloc (filevec[f].buffered_lines * sizeof (int));
  327.     }
  328.  
  329.   /* Set up equiv_count[F][I] as the number of lines in file F
  330.      that fall in equivalence class I.  */
  331.  
  332.   equiv_count[0] = (int *) xmalloc (filevec[0].equiv_max * sizeof (int));
  333.   bzero (equiv_count[0], filevec[0].equiv_max * sizeof (int));
  334.   equiv_count[1] = (int *) xmalloc (filevec[1].equiv_max * sizeof (int));
  335.   bzero (equiv_count[1], filevec[1].equiv_max * sizeof (int));
  336.  
  337.   for (i = 0; i < filevec[0].buffered_lines; ++i)
  338.     ++equiv_count[0][filevec[0].equivs[i]];
  339.   for (i = 0; i < filevec[1].buffered_lines; ++i)
  340.     ++equiv_count[1][filevec[1].equivs[i]];
  341.  
  342.   /* Set up tables of which lines are going to be discarded.  */
  343.  
  344.   discarded[0] = (char *) xmalloc (filevec[0].buffered_lines);
  345.   discarded[1] = (char *) xmalloc (filevec[1].buffered_lines);
  346.   bzero (discarded[0], filevec[0].buffered_lines);
  347.   bzero (discarded[1], filevec[1].buffered_lines);
  348.  
  349.   /* Mark to be discarded each line that matches no line of the other file.
  350.      If a line matches many lines, mark it as provisionally discardable.  */
  351.  
  352.   for (f = 0; f < 2; f++)
  353.     {
  354.       unsigned int end = filevec[f].buffered_lines;
  355.       char *discards = discarded[f];
  356.       int *counts = equiv_count[1 - f];
  357.       int *equivs = filevec[f].equivs;
  358.       unsigned int many = 5;
  359.       unsigned int tem = end / 64;
  360.  
  361.       /* Multiply MANY by approximate square root of number of lines.
  362.      That is the threshold for provisionally discardable lines.  */
  363.       while ((tem = tem >> 2) > 0)
  364.     many *= 2;
  365.  
  366.       for (i = 0; i < end; i++)
  367.     {
  368.       int nmatch;
  369.       if (equivs[i] == 0)
  370.         continue;
  371.       nmatch = counts[equivs[i]];
  372.       if (nmatch == 0)
  373.         discards[i] = 1;
  374.       else if (nmatch > many)
  375.         discards[i] = 2;
  376.     }
  377.     }
  378.  
  379.   /* Don't really discard the provisional lines except when they occur
  380.      in a run of discardables, with nonprovisionals at the beginning
  381.      and end.  */
  382.  
  383.   for (f = 0; f < 2; f++)
  384.     {
  385.       unsigned int end = filevec[f].buffered_lines;
  386.       register char *discards = discarded[f];
  387.  
  388.       for (i = 0; i < end; i++)
  389.     {
  390.       /* Cancel provisional discards not in middle of run of discards.  */
  391.       if (discards[i] == 2)
  392.         discards[i] = 0;
  393.       else if (discards[i] != 0)
  394.         {
  395.           /* We have found a nonprovisional discard.  */
  396.           register int j;
  397.           unsigned int length;
  398.           unsigned int provisional = 0;
  399.  
  400.           /* Find end of this run of discardable lines.
  401.          Count how many are provisionally discardable.  */
  402.           for (j = i; j < end; j++)
  403.         {
  404.           if (discards[j] == 0)
  405.             break;
  406.           if (discards[j] == 2)
  407.             ++provisional;
  408.         }
  409.  
  410.           /* Cancel provisional discards at end, and shrink the run.  */
  411.           while (j > i && discards[j - 1] == 2)
  412.         discards[--j] = 0, --provisional;
  413.  
  414.           /* Now we have the length of a run of discardable lines
  415.          whose first and last are not provisional.  */
  416.           length = j - i;
  417.  
  418.           /* If 1/4 of the lines in the run are provisional,
  419.          cancel discarding of all provisional lines in the run.  */
  420.           if (provisional * 4 > length)
  421.         {
  422.           while (j > i)
  423.             if (discards[--j] == 2)
  424.               discards[j] = 0;
  425.         }
  426.           else
  427.         {
  428.           register unsigned int consec;
  429.           unsigned int minimum = 1;
  430.           unsigned int tem = length / 4;
  431.  
  432.           /* MINIMUM is approximate square root of LENGTH/4.
  433.              A subrun of two or more provisionals can stand
  434.              when LENGTH is at least 16.
  435.              A subrun of 4 or more can stand when LENGTH >= 64.  */
  436.           while ((tem = tem >> 2) > 0)
  437.             minimum *= 2;
  438.           minimum++;
  439.  
  440.           /* Cancel any subrun of MINIMUM or more provisionals
  441.              within the larger run.  */
  442.           for (j = 0, consec = 0; j < length; j++)
  443.             if (discards[i + j] != 2)
  444.               consec = 0;
  445.             else if (minimum == ++consec)
  446.               /* Back up to start of subrun, to cancel it all.  */
  447.               j -= consec;
  448.             else if (minimum < consec)
  449.               discards[i + j] = 0;
  450.  
  451.           /* Scan from beginning of run
  452.              until we find 3 or more nonprovisionals in a row
  453.              or until the first nonprovisional at least 8 lines in.
  454.              Until that point, cancel any provisionals.  */
  455.           for (j = 0, consec = 0; j < length; j++)
  456.             {
  457.               if (j >= 8 && discards[i + j] == 1)
  458.             break;
  459.               if (discards[i + j] == 2)
  460.             consec = 0, discards[i + j] = 0;
  461.               else if (discards[i + j] == 0)
  462.             consec = 0;
  463.               else
  464.             consec++;
  465.               if (consec == 3)
  466.             break;
  467.             }
  468.  
  469.           /* I advances to the last line of the run.  */
  470.           i += length - 1;
  471.  
  472.           /* Same thing, from end.  */
  473.           for (j = 0, consec = 0; j < length; j++)
  474.             {
  475.               if (j >= 8 && discards[i - j] == 1)
  476.             break;
  477.               if (discards[i - j] == 2)
  478.             consec = 0, discards[i - j] = 0;
  479.               else if (discards[i - j] == 0)
  480.             consec = 0;
  481.               else
  482.             consec++;
  483.               if (consec == 3)
  484.             break;
  485.             }
  486.         }
  487.         }
  488.     }
  489.     }
  490.  
  491.   /* Actually discard the lines. */
  492.   for (f = 0; f < 2; f++)
  493.     {
  494.       char *discards = discarded[f];
  495.       unsigned int end = filevec[f].buffered_lines;
  496.       unsigned int j = 0;
  497.       for (i = 0; i < end; ++i)
  498.     if (no_discards || discards[i] == 0)
  499.       {
  500.         filevec[f].undiscarded[j] = filevec[f].equivs[i];
  501.         filevec[f].realindexes[j++] = i;
  502.       }
  503.     else
  504.       filevec[f].changed_flag[i] = 1;
  505.       filevec[f].nondiscarded_lines = j;
  506.     }
  507.  
  508.   free (discarded[1]);
  509.   free (discarded[0]);
  510.   free (equiv_count[1]);
  511.   free (equiv_count[0]);
  512. }
  513.  
  514. /* Adjust inserts/deletes of blank lines to join changes
  515.    as much as possible.
  516.  
  517.    We do something when a run of changed lines include a blank
  518.    line at one end and have an excluded blank line at the other.
  519.    We are free to choose which blank line is included.
  520.    `compareseq' always chooses the one at the beginning,
  521.    but usually it is cleaner to consider the following blank line
  522.    to be the "change".  The only exception is if the preceding blank line
  523.    would join this change to other changes.  */
  524.  
  525. int inhibit;
  526.  
  527. static void
  528. shift_boundaries (filevec)
  529.      struct file_data filevec[];
  530. {
  531.   int f;
  532.  
  533.   if (inhibit)
  534.     return;
  535.  
  536.   for (f = 0; f < 2; f++)
  537.     {
  538.       char *changed = filevec[f].changed_flag;
  539.       char *other_changed = filevec[1-f].changed_flag;
  540.       int i = 0;
  541.       int j = 0;
  542.       int i_end = filevec[f].buffered_lines;
  543.       int preceding = -1;
  544.       int other_preceding = -1;
  545.  
  546.       while (1)
  547.     {
  548.       int start, end, other_start;
  549.  
  550.       /* Scan forwards to find beginning of another run of changes.
  551.          Also keep track of the corresponding point in the other file.  */
  552.  
  553.       while (i < i_end && changed[i] == 0)
  554.         {
  555.           while (other_changed[j++])
  556.         /* Non-corresponding lines in the other file
  557.            will count as the preceding batch of changes.  */
  558.         other_preceding = j;
  559.           i++;
  560.         }
  561.  
  562.       if (i == i_end)
  563.         break;
  564.  
  565.       start = i;
  566.       other_start = j;
  567.  
  568.       while (1)
  569.         {
  570.           /* Now find the end of this run of changes.  */
  571.  
  572.           while (i < i_end && changed[i] != 0) i++;
  573.           end = i;
  574.  
  575.           /* If the first changed line matches the following unchanged one,
  576.          and this run does not follow right after a previous run,
  577.          and there are no lines deleted from the other file here,
  578.          then classify the first changed line as unchanged
  579.          and the following line as changed in its place.  */
  580.  
  581.           /* You might ask, how could this run follow right after another?
  582.          Only because the previous run was shifted here.  */
  583.  
  584.           if (end != i_end
  585.           && files[f].equivs[start] == files[f].equivs[end]
  586.           && !other_changed[j]
  587.           && end != i_end
  588.           && !((preceding >= 0 && start == preceding)
  589.                || (other_preceding >= 0
  590.                && other_start == other_preceding)))
  591.         {
  592.           changed[end++] = 1;
  593.           changed[start++] = 0;
  594.           ++i;
  595.           /* Since one line-that-matches is now before this run
  596.              instead of after, we must advance in the other file
  597.              to keep in synch.  */
  598.           ++j;
  599.         }
  600.           else
  601.         break;
  602.         }
  603.  
  604.       preceding = i;
  605.       other_preceding = j;
  606.     }
  607.     }
  608. }
  609.  
  610. /* Cons an additional entry onto the front of an edit script OLD.
  611.    LINE0 and LINE1 are the first affected lines in the two files (origin 0).
  612.    DELETED is the number of lines deleted here from file 0.
  613.    INSERTED is the number of lines inserted here in file 1.
  614.  
  615.    If DELETED is 0 then LINE0 is the number of the line before
  616.    which the insertion was done; vice versa for INSERTED and LINE1.  */
  617.  
  618. static struct change *
  619. add_change (line0, line1, deleted, inserted, old)
  620.      int line0, line1, deleted, inserted;
  621.      struct change *old;
  622. {
  623.   struct change *new = (struct change *) xmalloc (sizeof (struct change));
  624.  
  625.   new->line0 = line0;
  626.   new->line1 = line1;
  627.   new->inserted = inserted;
  628.   new->deleted = deleted;
  629.   new->link = old;
  630.   return new;
  631. }
  632.  
  633. /* Scan the tables of which lines are inserted and deleted,
  634.    producing an edit script in reverse order.  */
  635.  
  636. static struct change *
  637. build_reverse_script (filevec)
  638.      struct file_data filevec[];
  639. {
  640.   struct change *script = 0;
  641.   char *changed0 = filevec[0].changed_flag;
  642.   char *changed1 = filevec[1].changed_flag;
  643.   int len0 = filevec[0].buffered_lines;
  644.   int len1 = filevec[1].buffered_lines;
  645.  
  646.   /* Note that changedN[len0] does exist, and contains 0.  */
  647.  
  648.   int i0 = 0, i1 = 0;
  649.  
  650.   while (i0 < len0 || i1 < len1)
  651.     {
  652.       if (changed0[i0] || changed1[i1])
  653.     {
  654.       int line0 = i0, line1 = i1;
  655.  
  656.       /* Find # lines changed here in each file.  */
  657.       while (changed0[i0]) ++i0;
  658.       while (changed1[i1]) ++i1;
  659.  
  660.       /* Record this change.  */
  661.       script = add_change (line0, line1, i0 - line0, i1 - line1, script);
  662.     }
  663.  
  664.       /* We have reached lines in the two files that match each other.  */
  665.       i0++, i1++;
  666.     }
  667.  
  668.   return script;
  669. }
  670.  
  671. /* Scan the tables of which lines are inserted and deleted,
  672.    producing an edit script in forward order.  */
  673.  
  674. static struct change *
  675. build_script (filevec)
  676.      struct file_data filevec[];
  677. {
  678.   struct change *script = 0;
  679.   char *changed0 = filevec[0].changed_flag;
  680.   char *changed1 = filevec[1].changed_flag;
  681.   int len0 = filevec[0].buffered_lines;
  682.   int len1 = filevec[1].buffered_lines;
  683.   int i0 = len0, i1 = len1;
  684.  
  685.   /* Note that changedN[-1] does exist, and contains 0.  */
  686.  
  687. #if 0 /* Unnecessary since a line includes its trailing newline.  */
  688.   /* In RCS comparisons, making the existence or nonexistence of trailing
  689.      newlines really matter. */
  690.   if (output_style == OUTPUT_RCS
  691.       && filevec[0].missing_newline != filevec[1].missing_newline)
  692.     changed0[len0 - 1] = changed1[len1 - 1] = 1;
  693. #endif
  694.  
  695.   while (i0 >= 0 || i1 >= 0)
  696.     {
  697.       if (changed0[i0 - 1] || changed1[i1 - 1])
  698.     {
  699.       int line0 = i0, line1 = i1;
  700.  
  701.       /* Find # lines changed here in each file.  */
  702.       while (changed0[i0 - 1]) --i0;
  703.       while (changed1[i1 - 1]) --i1;
  704.  
  705.       /* Record this change.  */
  706.       script = add_change (i0, i1, line0 - i0, line1 - i1, script);
  707.     }
  708.  
  709.       /* We have reached lines in the two files that match each other.  */
  710.       i0--, i1--;
  711.     }
  712.  
  713.   return script;
  714. }
  715.  
  716. #include <invent.h>
  717. /* Return size of main memory in bytes */
  718. memsize(){
  719.   inventory_t *getinvent(void);
  720.   inventory_t *sp;
  721.   static int sz = 0;
  722.  
  723.   if (sz == 0)
  724.     {
  725.       while ((sp = getinvent()) != 0)
  726.         {
  727.           if (sp->inv_class == INV_MEMORY && sp->inv_type == INV_MAIN)
  728.             {
  729.               sz = sp->inv_state;
  730.               break;
  731.             }
  732.         }
  733.     }
  734.  
  735.   if (sz == 0)
  736.     sz = 8*1024*1024;    /* 8 MByte default main memory size */
  737.  
  738.   return sz;
  739. }
  740.  
  741. #include <signal.h>
  742. #include <unistd.h>
  743. #include <sys/wait.h>
  744.  
  745. int
  746. tryodiff (char *cmd, int argc, char **argv)
  747. {
  748.     int    status, pid, w, sig;
  749.     struct sigaction oldistat, oldqstat, oldcstat, newiqstat, newcstat, newustat;
  750.  
  751.     /*
  752.      * ignore INT and QUIT, saving previous handlers and masks
  753.      */
  754.     if (sigaction(SIGINT,NULL,&oldistat) == -1)
  755.         return(-1);
  756.  
  757.     newiqstat.sa_handler = SIG_IGN;
  758.     newiqstat.sa_flags = 0;
  759.     newcstat.sa_handler = SIG_DFL;
  760.     newcstat.sa_flags = 0;
  761.  
  762.     if ( (sigaction(SIGINT,&newiqstat,&oldistat) == -1) ||
  763.            (sigaction(SIGQUIT,&newiqstat,&oldqstat) == -1) ||
  764.            (sigaction(SIGCLD,&newcstat,&oldcstat) == -1) ) {
  765.         return(-1);
  766.     }
  767.  
  768.     if ((pid = fork()) == 0) {
  769.         char *emsg = ": sigaction internal botch\n";
  770.         /* Child process */
  771.         /* reinstall old handlers and masks. */
  772.         (void) sigaction(SIGINT,&oldistat,NULL);
  773.         (void) sigaction(SIGQUIT,&oldqstat,NULL);
  774.         (void) sigaction(SIGCLD,&oldcstat,NULL);
  775.         argv[0] = cmd;
  776.         (void) execvp(argv[0], argv);
  777.  
  778.         /* oops - exec failed - tell parent that we didn't
  779.          * do anything useful by committing SIGUSR2 harikari.
  780.          */
  781.         newustat.sa_handler = SIG_DFL;
  782.         newustat.sa_flags = 0;
  783.         sigaction(SIGUSR2,&newustat,NULL);
  784.         kill(getpid(), SIGUSR2);
  785.         /* should be dead by now -- but just in case ... */
  786.         /* Avoid stdio: parent process's buffers are inherited. */
  787.         write (fileno (stderr), program, strlen (program));
  788.         write (fileno (stderr), emsg, strlen(emsg));
  789.         _exit(127);    /* dont double fflush stdio */
  790.         /* NOTREACHED */
  791.     }
  792.     
  793.     if (pid < 0) {
  794.         w = -1;                /* fork failed */
  795.     } else {
  796.         w = waitpid(pid,&status,0);
  797.     }
  798.  
  799.     /* reinstall old handlers and masks. */
  800.     (void) sigaction(SIGINT,&oldistat,NULL);
  801.     (void) sigaction(SIGQUIT,&oldqstat,NULL);
  802.     (void) sigaction(SIGCLD,&oldcstat,NULL);
  803.  
  804.     sig = WTERMSIG(status);
  805.  
  806.     if (w == -1)
  807.         return -1;            /* fork failed */
  808.     else if (WIFSIGNALED(status) && sig == SIGUSR2)
  809.         return -1;            /* exec failed */
  810.     else if (WIFEXITED(status))
  811.         return WEXITSTATUS(status);    /* normal odiff exit */
  812.     else if (WIFSIGNALED(status) && (sig == SIGINT || sig == SIGQUIT))
  813.         kill(getpid(), sig);        /* reissue held off signal to self */
  814.     return 2;                /* problems */
  815. }
  816.  
  817. extern int xargc;
  818. extern char **xargv;
  819. extern int gnudiffopts;
  820.  
  821. /* Report the differences of two files.  DEPTH is the current directory
  822.    depth. */
  823. int
  824. diff_2_files (filevec, depth)
  825.      struct file_data filevec[];
  826.      int depth;
  827. {
  828.   int diags;
  829.   int i;
  830.   struct change *e, *p;
  831.   struct change *script;
  832.   int binary;
  833.   int changes;
  834.  
  835.   /* See if the two named files are actually the same physical file.
  836.      If so, we know they are identical without actually reading them.  */
  837.  
  838.   if (output_style != OUTPUT_IFDEF
  839.       && filevec[0].stat.st_ino == filevec[1].stat.st_ino
  840.       && filevec[0].stat.st_dev == filevec[1].stat.st_dev)
  841.     return 0;
  842.  
  843.   /* See if the two named files are too big to fit in memory
  844.      comfortably.  Since GNU diff reads/mmaps both files into its
  845.      virtual addr space, it pages heavily on huge files.  The old BSD
  846.      derived "odiff" is much more space (swap and main memory)
  847.      efficient.    But if the files fit in main memory, then the GNU
  848.      diff is quite a bit faster - as much as 2x to 3x faster.  Arbitrarily
  849.      consider 1/4 Main Memory size as too big.  User can force choice:
  850.      specify -H always gets GNU diff, use odiff always gets the old BSD diff.
  851.      Return of -1 from tryodiff means that odiff wasn't even run - so we
  852.      should try further here instead. */
  853.  
  854.   if (gnudiffopts == 0 &&
  855.       (filevec[0].stat.st_size + filevec[1].stat.st_size) > memsize()/4 )
  856.     {
  857.       int ret;
  858.       xargv[xargc] = filevec[0].name;
  859.       xargv[xargc+1] = filevec[1].name;
  860.       if ((ret = tryodiff("odiff",xargc,xargv)) != -1)
  861.         return ret;
  862.     }
  863.  
  864.   files_are_identical = 0;
  865.  
  866.   binary = read_files (filevec);
  867.  
  868.   if (files_are_identical)
  869.     {
  870.       for (i = 0; i < 2; ++i)
  871.     if (filevec[i].buffer)
  872.           {
  873.             if (filevec[i].buffer_was_mmapped)
  874.               munmap (filevec[i].buffer, filevec[i].bufsize + 2);
  875.             else
  876.               free (filevec[i].buffer);
  877.           }
  878.       return 0;
  879.     }
  880.  
  881.   /* If we have detected that file 0 is a binary file,
  882.      compare the two files as binary.  This can happen
  883.      only when the first chunk is read.
  884.      Also, -q means treat all files as binary.  */
  885.  
  886.   if (binary || no_details_flag)
  887.     {
  888.       int differs = (filevec[0].buffered_chars != filevec[1].buffered_chars
  889.              || bcmp (filevec[0].buffer, filevec[1].buffer,
  890.                   filevec[1].buffered_chars));
  891.       if (differs) 
  892.     message (binary ? "Binary files %s and %s differ\n"
  893.          : "Files %s and %s differ\n",
  894.          filevec[0].name, filevec[1].name);
  895.  
  896.       for (i = 0; i < 2; ++i)
  897.     if (filevec[i].buffer)
  898.           {
  899.             if (filevec[i].buffer_was_mmapped)
  900.               munmap (filevec[i].buffer, filevec[i].bufsize + 2);
  901.             else
  902.               free (filevec[i].buffer);
  903.           }
  904.       return differs;
  905.     }
  906.  
  907.   /* Allocate vectors for the results of comparison:
  908.      a flag for each line of each file, saying whether that line
  909.      is an insertion or deletion.
  910.      Allocate an extra element, always zero, at each end of each vector.  */
  911.  
  912.   filevec[0].changed_flag = (char *) xmalloc (filevec[0].buffered_lines + 2);
  913.   filevec[1].changed_flag = (char *) xmalloc (filevec[1].buffered_lines + 2);
  914.   bzero (filevec[0].changed_flag, filevec[0].buffered_lines + 2);
  915.   bzero (filevec[1].changed_flag, filevec[1].buffered_lines + 2);
  916.   filevec[0].changed_flag++;
  917.   filevec[1].changed_flag++;
  918.  
  919.   /* Some lines are obviously insertions or deletions
  920.      because they don't match anything.  Detect them now,
  921.      and avoid even thinking about them in the main comparison algorithm.  */
  922.  
  923.   discard_confusing_lines (filevec);
  924.  
  925.   /* Now do the main comparison algorithm, considering just the
  926.      undiscarded lines.  */
  927.  
  928.   xvec = filevec[0].undiscarded;
  929.   yvec = filevec[1].undiscarded;
  930.   diags = filevec[0].nondiscarded_lines + filevec[1].nondiscarded_lines + 3;
  931.   fdiag = (int *) xmalloc (diags * sizeof (int));
  932.   fdiag += filevec[1].nondiscarded_lines + 1;
  933.   bdiag = (int *) xmalloc (diags * sizeof (int));
  934.   bdiag += filevec[1].nondiscarded_lines + 1;
  935.  
  936.   files[0] = filevec[0];
  937.   files[1] = filevec[1];
  938.  
  939.   compareseq (0, filevec[0].nondiscarded_lines,
  940.           0, filevec[1].nondiscarded_lines);
  941.  
  942.   bdiag -= filevec[1].nondiscarded_lines + 1;
  943.   free (bdiag);
  944.   fdiag -= filevec[1].nondiscarded_lines + 1;
  945.   free (fdiag);
  946.  
  947.   /* Modify the results slightly to make them prettier
  948.      in cases where that can validly be done.  */
  949.  
  950.   shift_boundaries (filevec);
  951.  
  952.   /* Get the results of comparison in the form of a chain
  953.      of `struct change's -- an edit script.  */
  954.  
  955.   if (output_style == OUTPUT_ED)
  956.     script = build_reverse_script (filevec);
  957.   else
  958.     script = build_script (filevec);
  959.  
  960.   if (script || output_style == OUTPUT_IFDEF)
  961.     {
  962.       setup_output (files[0].name, files[1].name, depth);
  963.  
  964.       switch (output_style)
  965.     {
  966.     case OUTPUT_CONTEXT:
  967.       print_context_header (files, 0);
  968.       print_context_script (script, 0);
  969.       break;
  970.  
  971.     case OUTPUT_UNIFIED:
  972.       print_context_header (files, 1);
  973.       print_context_script (script, 1);
  974.       break;
  975.  
  976.     case OUTPUT_ED:
  977.       print_ed_script (script);
  978.       break;
  979.  
  980.     case OUTPUT_FORWARD_ED:
  981.       pr_forward_ed_script (script);
  982.       break;
  983.  
  984.     case OUTPUT_RCS:
  985.       print_rcs_script (script);
  986.       break;
  987.  
  988.     case OUTPUT_NORMAL:
  989.       print_normal_script (script);
  990.       break;
  991.  
  992.     case OUTPUT_IFDEF:
  993.       print_ifdef_script (script);
  994.       break;
  995.     }
  996.  
  997.       finish_output ();
  998.     }
  999.  
  1000.   /* Set CHANGES if we had any diffs that were printed.
  1001.      If some changes are being ignored, we must scan the script to decide.  */
  1002.   if (ignore_blank_lines_flag || ignore_regexp)
  1003.     {
  1004.       struct change *next = script;
  1005.       changes = 0;
  1006.  
  1007.       while (next && changes == 0)
  1008.     {
  1009.       struct change *this, *end;
  1010.       int first0, last0, first1, last1, deletes, inserts;
  1011.  
  1012.       /* Find a set of changes that belong together.  */
  1013.       this = next;
  1014.       end = find_change (next);
  1015.  
  1016.       /* Disconnect them from the rest of the changes,
  1017.          making them a hunk, and remember the rest for next iteration.  */
  1018.       next = end->link;
  1019.       end->link = NULL;
  1020.  
  1021.       /* Determine whether this hunk was printed.  */
  1022.       analyze_hunk (this, &first0, &last0, &first1, &last1,
  1023.             &deletes, &inserts);
  1024.  
  1025.       /* Reconnect the script so it will all be freed properly.  */
  1026.       end->link = next;
  1027.  
  1028.       if (deletes || inserts)
  1029.         changes = 1;
  1030.     }
  1031.     }
  1032.   else
  1033.     changes = (script != 0);
  1034.  
  1035.   for (i = 1; i >= 0; --i)
  1036.     {
  1037.       free (filevec[i].realindexes);
  1038.       free (filevec[i].undiscarded);
  1039.     }
  1040.  
  1041.   for (i = 1; i >= 0; --i)
  1042.     free (--filevec[i].changed_flag);
  1043.  
  1044.   for (i = 1; i >= 0; --i)
  1045.     free (filevec[i].equivs);
  1046.  
  1047.   for (i = 0; i < 2; ++i)
  1048.     {
  1049.       if (filevec[i].buffer != 0)
  1050.         {
  1051.           if (filevec[i].buffer_was_mmapped)
  1052.             munmap (filevec[i].buffer, filevec[i].bufsize + 2);
  1053.           else
  1054.             free (filevec[i].buffer);
  1055.         }
  1056.       free (filevec[i].linbuf);
  1057.     }
  1058.  
  1059.   for (e = script; e; e = p)
  1060.     {
  1061.       p = e->link;
  1062.       free (e);
  1063.     }
  1064.  
  1065.   if (! ROBUST_OUTPUT_STYLE (output_style)
  1066.       /* For -D, invent newlines silently.  That's ok in C code.  */
  1067.       && output_style != OUTPUT_IFDEF)
  1068.     for (i = 0; i < 2; ++i)
  1069.       if (filevec[i].missing_newline)
  1070.     {
  1071.       error ("No newline at end of file %s", filevec[i].name, "");
  1072.       changes = 2;
  1073.     }
  1074.  
  1075.   return changes;
  1076. }
  1077.